package com.rickpan.controller;

import com.rickpan.common.Result;
import com.rickpan.entity.Note;
import com.rickpan.service.NoteService;
import com.rickpan.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 便签管理Controller
 *
 * @author RickPan Team
 * @since 2024-01-06
 */
@Slf4j
@RestController
@RequestMapping("/api/notes")
@Tag(name = "便签管理", description = "便签相关接口")
public class NoteController {

    @Autowired
    private NoteService noteService;

    /**
     * 创建便签
     */
    @PostMapping
    @Operation(summary = "创建便签", description = "创建新的便签")
    public Result<Note> createNote(@RequestBody Map<String, Object> request,
                                  HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            String title = (String) request.get("title");
            String content = (String) request.get("content");
            String markdownContent = (String) request.get("markdownContent");
            Long folderId = request.get("folderId") != null ?
                Long.valueOf(request.get("folderId").toString()) : null;

            Note note = noteService.createNote(userId, title, content, markdownContent, folderId);
            return Result.success("创建成功", note);
        } catch (Exception e) {
            log.error("创建便签失败", e);
            return Result.error("创建便签失败: " + e.getMessage());
        }
    }

    /**
     * 获取便签列表
     */
    @GetMapping
    @Operation(summary = "获取便签列表", description = "分页获取便签列表")
    public Result<Map<String, Object>> getNotes(@RequestParam(required = false) Long folderId,
                                               @RequestParam(required = false) String search,
                                               @RequestParam(required = false) Boolean isFavorite,
                                               @RequestParam(required = false) Boolean hasReminder,
                                               @RequestParam(defaultValue = "1") Integer page,
                                               @RequestParam(defaultValue = "20") Integer size,
                                               HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            Page<Note> notePage = noteService.getNotes(userId, folderId, search, isFavorite, hasReminder, page, size);

            // 转换为前端期望的格式
            Map<String, Object> result = new HashMap<>();
            result.put("records", notePage.getContent());
            result.put("total", notePage.getTotalElements());
            result.put("current", notePage.getNumber() + 1);
            result.put("size", notePage.getSize());
            result.put("pages", notePage.getTotalPages());

            return Result.success(result);
        } catch (Exception e) {
            log.error("获取便签列表失败", e);
            return Result.error("获取便签列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取最近便签
     */
    @GetMapping("/recent")
    @Operation(summary = "获取最近便签", description = "获取最近编辑的便签")
    public Result<List<Note>> getRecentNotes(@RequestParam(defaultValue = "10") Integer limit,
                                            HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            List<Note> notes = noteService.getRecentNotes(userId, limit);
            return Result.success(notes);
        } catch (Exception e) {
            log.error("获取最近便签失败", e);
            return Result.error("获取最近便签失败: " + e.getMessage());
        }
    }

    /**
     * 获取收藏便签
     */
    @GetMapping("/favorites")
    @Operation(summary = "获取收藏便签", description = "获取收藏的便签")
    public Result<List<Note>> getFavoriteNotes(@RequestParam(defaultValue = "10") Integer limit,
                                              HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            List<Note> notes = noteService.getFavoriteNotes(userId, limit);
            return Result.success(notes);
        } catch (Exception e) {
            log.error("获取收藏便签失败", e);
            return Result.error("获取收藏便签失败: " + e.getMessage());
        }
    }

    /**
     * 更新便签
     */
    @PutMapping("/{noteId}")
    @Operation(summary = "更新便签", description = "更新便签内容")
    public Result<Note> updateNote(@PathVariable Long noteId,
                                  @RequestBody Map<String, Object> request,
                                  HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            String title = (String) request.get("title");
            String content = (String) request.get("content");
            String markdownContent = (String) request.get("markdownContent");
            Boolean isFavorite = (Boolean) request.get("isFavorite");

            Note note = noteService.updateNote(noteId, userId, title, content, markdownContent, isFavorite);
            return Result.success("更新成功", note);
        } catch (Exception e) {
            log.error("更新便签失败", e);
            return Result.error("更新便签失败: " + e.getMessage());
        }
    }

    /**
     * 删除便签
     */
    @DeleteMapping("/{noteId}")
    @Operation(summary = "删除便签", description = "删除指定便签")
    public Result<String> deleteNote(@PathVariable Long noteId,
                                    HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            boolean success = noteService.deleteNote(noteId, userId);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("便签不存在或无权删除");
            }
        } catch (Exception e) {
            log.error("删除便签失败", e);
            return Result.error("删除便签失败: " + e.getMessage());
        }
    }

    /**
     * 切换收藏状态
     */
    @PostMapping("/{noteId}/toggle-favorite")
    @Operation(summary = "切换收藏状态", description = "切换便签的收藏状态")
    public Result<Note> toggleFavorite(@PathVariable Long noteId,
                                       HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            Note note = noteService.toggleFavorite(noteId, userId);
            return Result.success("切换成功", note);
        } catch (Exception e) {
            log.error("切换收藏状态失败", e);
            return Result.error("切换收藏状态失败: " + e.getMessage());
        }
    }

    /**
     * 获取便签统计信息
     */
    @GetMapping("/stats")
    @Operation(summary = "获取便签统计信息", description = "获取用户便签的统计数据")
    public Result<Map<String, Object>> getNoteStats(HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            NoteService.NoteStats noteStats = noteService.getNoteStats(userId);

            Map<String, Object> result = new HashMap<>();
            result.put("totalNotes", noteStats.getTotalNotes());
            result.put("favoriteNotes", noteStats.getFavoriteNotes());
            result.put("reminderNotes", 0); // 暂时设为0，后续实现提醒功能
            result.put("todayNotes", noteStats.getTodayNotes());

            return Result.success(result);
        } catch (Exception e) {
            log.error("获取便签统计信息失败", e);
            return Result.error("获取便签统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 导出便签为Markdown文件
     */
    @GetMapping("/{noteId}/export/markdown")
    @Operation(summary = "导出便签为Markdown", description = "将便签内容导出为Markdown文件")
    public ResponseEntity<String> exportNoteToMarkdown(@PathVariable Long noteId,
                                                      HttpServletRequest httpRequest) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            log.info("用户 {} 导出便签 {} 为Markdown", userId, noteId);

            // 先获取便签信息（不增加查看次数）
            Note note = noteService.getNoteById(noteId, userId);
            String fileName = sanitizeFileName(note.getTitle()) + ".md";

            // 导出Markdown内容
            String markdownContent = noteService.exportNoteToMarkdown(noteId, userId);

            log.info("导出便签成功: noteId={}, fileName={}, contentLength={}",
                    noteId, fileName, markdownContent.length());

            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment; filename*=UTF-8''" +
                           java.net.URLEncoder.encode(fileName, "UTF-8"))
                    .header("Content-Type", "text/plain; charset=UTF-8")
                    .header("Access-Control-Expose-Headers", "Content-Disposition")
                    .body(markdownContent);

        } catch (Exception e) {
            log.error("导出便签为Markdown失败: noteId={}", noteId, e);
            return ResponseEntity.status(500).body("导出失败: " + e.getMessage());
        }
    }

    /**
     * 清理文件名，移除不安全字符
     */
    private String sanitizeFileName(String fileName) {
        if (fileName == null || fileName.trim().isEmpty()) {
            return "便签_" + System.currentTimeMillis();
        }

        // 移除文件名中的不安全字符
        String sanitized = fileName.replaceAll("[\\\\/:*?\"<>|]", "_");

        // 限制文件名长度
        if (sanitized.length() > 100) {
            sanitized = sanitized.substring(0, 100);
        }

        return sanitized;
    }
}
